<template>
  <div class="home">
    <!-- <div class="buttons-container">
      <button v-for="interval in intervals" :key="interval" @click="changeInterval(interval)">{{ interval }}</button>
    </div> -->
    <div id="container-demo1">
    </div>
  </div>
</template>

<script>
import { createChart } from 'lightweight-charts';

import moment from 'moment';

export default {
  name: 'HomeView',

  data() {
    return {
      intervals: ['1D', '1W', '1M', '1Y'],
      currentInterval: '1D',
      chart: null,
      series: null,
      _earliestDate: null,
      _data: [],
      areaSeries: null,
      volumeSeries: null,
      _volumes: [],
    };
  },

  mounted() {
    this.$nextTick(() => {
      this.init();
    });

  },
  methods: {

    // 初始化图表
    init() {

      let randomFactor = 25 + Math.random() * 25;
      const samplePoint = i =>
        i *
        (0.5 +
          Math.sin(i / 10) * 0.2 +
          Math.sin(i / 20) * 0.4 +
          Math.sin(i / randomFactor) * 0.8 +
          Math.sin(i / 500) * 0.5) +
        200;

      function generateLineData(numberOfPoints = 500, endDate) {
        randomFactor = 25 + Math.random() * 25;
        const res = [];
        const date = endDate || new Date(Date.UTC(2018, 0, 1, 12, 0, 0, 0));
        date.setUTCDate(date.getUTCDate() - numberOfPoints - 1);
        for (let i = 0; i < numberOfPoints; ++i) {
          const time = date.getTime() / 1000;
          const value = samplePoint(i);
          res.push({
            time,
            value,
          });
          date.setUTCDate(date.getUTCDate() + 1);
        }

        return res;
      }
      function randomNumber(min, max) {
        return Math.random() * (max - min) + min;
      }

      function randomBar(lastClose) {
        const open = +randomNumber(lastClose * 0.95, lastClose * 1.05).toFixed(2);
        const close = +randomNumber(open * 0.95, open * 1.05).toFixed(2);
        const high = +randomNumber(
          Math.max(open, close),
          Math.max(open, close) * 1.1
        ).toFixed(2);
        const low = +randomNumber(
          Math.min(open, close) * 0.9,
          Math.min(open, close)
        ).toFixed(2);
        return {
          open,
          high,
          low,
          close,
        };
      }

      function generateCandleData(numberOfPoints = 250, endDate) {
        const lineData = generateLineData(numberOfPoints, endDate);
        let lastClose = lineData[0].value;
        return lineData.map(d => {
          const candle = randomBar(lastClose);
          lastClose = candle.close;
          return {
            time: d.time,
            low: candle.low,
            high: candle.high,
            open: candle.open,
            close: candle.close,
            volumeTime: moment(d.time * 1000).format('YYYY-MM-DD'),
            volume: randomNumber(1000000, 100)
          };
        });
      }

      class Datafeed {
        constructor() {
          this._earliestDate = new Date(Date.UTC(2018, 0, 1, 12, 0, 0, 0));
          this._data = [];
        }

        getBars(numberOfExtraBars) {
          const historicalData = generateCandleData(
            numberOfExtraBars,
            this._earliestDate
          );
          console.log('historicalData', historicalData);
          this._data = [...historicalData, ...this._data];
          this._earliestDate = new Date(historicalData[0].time * 1000);
          // console.log('this._data', this._data);
          return this._data;
        }

      }

      const chartOptions = {
        layout: {
          textColor: 'white',
          background: { type: 'solid', color: 'black' },
        },
      };

      const container = document.getElementById('container-demo1');
      /** @type {import('lightweight-charts').IChartApi} */
      const chart = createChart(container, chartOptions);

      const series = chart.addCandlestickSeries({
        upColor: '#26a69a',
        downColor: '#ef5350',
        borderVisible: false,
        wickUpColor: '#26a69a',
        wickDownColor: '#ef5350',
      });

      // 设置交易量
      const areaSeries = chart.addAreaSeries({
        topColor: '#2962FF',
        bottomColor: 'rgba(41, 98, 255, 0.28)',
        lineColor: '#2962FF',
        lineWidth: 2,
        priceFormat: {
          type: 'volume',
        },
      });
      areaSeries.priceScale().applyOptions({
        scaleMargins: {
          // positioning the price scale for the area series
          top: 0.1,
          bottom: 0.4,
        },
      });

      const volumeSeries = chart.addHistogramSeries({
        color: '#26a69a',
        priceFormat: {
          type: 'volume',
        },
        priceScaleId: '', // set as an overlay by setting a blank priceScaleId
        // set the positioning of the volume series
        scaleMargins: {
          top: 0.7, // highest point of the series will be 70% away from the top
          bottom: 0,
        },
      });
      volumeSeries.priceScale().applyOptions({
        scaleMargins: {
          top: 0.7, // highest point of the series will be 70% away from the top
          bottom: 0,
        },
      });

      const datafeed = new Datafeed();
      // console.log('初始化数据', datafeed.getBars(200));
      this._data = datafeed.getBars(200);
      // 初始化数据
      series.setData(this._data);

      // 设置交易量
      const getVolumes = () => {
        const _data = this._data.map(d => {
          return {
            time: d.volumeTime,
            value: d.volume,
            color: Math.random() < 0.5 ? '#26a69a' : '#ef5350'
          }
        })
        volumeSeries.setData(_data);
      }
      getVolumes();

      chart.timeScale().fitContent();
      // 监听图表的区间的变化 当变化的时候 添加数据
      chart.timeScale().subscribeVisibleLogicalRangeChange(logicalRange => {
        // console.log('logicalRange', logicalRange);
        if (logicalRange.from < 10) {
          // load more data
          const numberBarsToLoad = 50 - logicalRange.from;
          const data = datafeed.getBars(numberBarsToLoad);
          this._data = data
          setTimeout(() => {
            series.setData(data);
            getVolumes();
          }, 250); // add a loading delay
        }
      });

      // 添加工具提示
      const toolTipWidth = 100;
      const toolTipHeight = 70;
      const toolTipMargin = 15;

      const toolTip = document.createElement('div');
      toolTip.style = `width: ${toolTipWidth}px; height:${toolTipHeight}px; position: absolute; display: none; padding: 15px; box-sizing: border-box; font-size: 12px; text-align: left; z-index: 1000; top: 12px; left: 12px; pointer-events: none; border: 1px solid; border-radius: 2px;font-family: -apple-system, BlinkMacSystemFont, 'Trebuchet MS', Roboto, Ubuntu, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale;`;
      toolTip.style.background = 'black';
      toolTip.style.color = 'white';
      toolTip.style.borderColor = 'rgba( 38, 166, 154, 1)';
      container.appendChild(toolTip);

      // 添加十字光标
      chart.subscribeCrosshairMove(param => {

        if (
          param.point === undefined ||
          !param.time ||
          param.point.x < 0 ||
          param.point.x > container.clientWidth ||
          param.point.y < 0 ||
          param.point.y > container.clientHeight
        ) {
          toolTip.style.display = 'none';
        } else {
          // console.log('鼠标参数', param);

          const dateStr = param.time;
          toolTip.style.display = 'block';
          const data = param.seriesData.get(series);
          const price = data?.value !== undefined ? data?.value : data?.close;
          toolTip.innerHTML = `
              <div style="font-size: 24px; margin: 4px 0px; color: ${'white'}">
              ${Math.round(100 * price) / 100}
              </div>
              <div style="color: ${'white'}">
              ${moment(dateStr * 1000).format('YYYY/MM/DD')} 
              </div>
           `;

          const y = param.point.y + container.offsetTop;
          let left = param.point.x + container.offsetLeft + toolTipMargin;
          if (left > container.clientWidth - toolTipWidth) {
            left = param.point.x + container.offsetLeft - toolTipMargin - toolTipWidth;
          }

          let top = y + toolTipMargin;
          if (top > container.clientHeight - toolTipHeight) {
            top = y - toolTipHeight - toolTipMargin;
          }
          toolTip.style.left = left + 'px';
          toolTip.style.top = top + 'px';
        }
        // 设置图表的区间
        // chart.timeScale().fitContent()
      });

      this.chart = chart;
      this.series = series;
      chart.timeScale().fitContent();
    }
  }

}
</script>


<style lang="scss" scoped>
.home {
  width: 100%;
  height: 100%;

  #container-demo1 {
    width: 100%;
    border: 1px solid red;
    height: 300px;
  }
}

::v-deep #tv-attr-logo {
  display: none;
}
</style>